/**
 * 
 */

package com.shy.portal.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shy.base.controller.AbsController;
import com.shy.base.util.BeanUtil;
import com.shy.base.vo.AppConstants;
import com.shy.base.vo.EasyuiPagerVo;
import com.shy.base.vo.PagerFilter;
import com.shy.portal.entity.Menu;
import com.shy.portal.service.MenuService;
import com.shy.portal.utils.Data2TreeVoUtils;
import com.shy.portal.vo.RoleMenuVo;

/**
 * <p>
 * Title:MenuController
 * </p>
 * <p>
 * Description:菜单管理控制器
 * </p>
 * <p>
 * Company:ipebg
 * </p>
 * 
 * @author H2013788
 */
@Controller
@RequestMapping("/menu")
public class MenuController extends AbsController {

	/**
     * log
     */
	private Logger logger = LogManager.getLogger(this.getClass());

    /**
     * service层
     */
    @Resource
    private MenuService menuService;

    /**
     * 请求菜单列表页面
     * 
     * @return 菜单页面
     * @author H2013788
     */
    @RequestMapping("/list_page")
    public String showMenuListPage() {
        return "portal/menu_list";
    }

    /**
     * 異步加载菜单列表数据
     * 
     * @param menu
     *            查询條件
     * @param page
     *            頁
     * @param rows
     *            行
     * @author H2013788
     */
    @RequestMapping("/list_data")
    public void loadMenuList(Menu menu, Integer page, Integer rows, HttpServletResponse response) {
        PagerFilter pagerFilter = getPageable(rows == null ? 10L : rows);
        pagerFilter.setPagePer(null == page ? 1 : page);
        //pagerFilter = menuService.listMenuByPager(menu, pagerFilter);
        LinkedHashMap<String, String> orderBy = new LinkedHashMap<String, String>();
        orderBy.put("menuCode", PagerFilter.DIRECTION_ASC);
        pagerFilter.setOrderby(orderBy);
        //使用通用查询方法
        pagerFilter = menuService.listByPager(menu, null, pagerFilter);
        writeResponse(new StringBuffer(gsonDateTimeExpose.toJson(new EasyuiPagerVo(pagerFilter))), response);
    }

    /**
     * 菜单預编辑，按照ID查询菜单信息
     * 
     * @param id
     *            菜单ID
     * @author H2013788
     */
    @RequestMapping("/edit_menu")
    public void editMenu(Integer id, HttpServletResponse response) {
        if (null != id) {
            Menu menu = menuService.getById(id);
            writeResponse(new StringBuffer(gsonDateTimeExpose.toJson(menu)), response);
        } else {
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.GET_OBJECT_NULL), response);
        }
    }

    /**
     * 保存菜单信息，用於新增或编辑菜单
     * 
     * @param menu
     *            菜单實体封裝
     * @author H2013788
     */
    @RequestMapping("/save_menu")
    public void saveMenu(Menu menu, HttpServletResponse response) {
        if (null == menu) {
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
        } else {
            try {
                if (null != menu.getId()) {
                    if (null != menu.getParent() && null != menu.getParent().getId()) {
                        Menu parent = menuService.getById(menu.getParent().getId());
                        menu.setParent(parent);
                        menu.setLevel(parent.getLevel() + 1);
                    }else{
                        menu.setParent(null);
                        menu.setLevel(1);
                    }
                    Menu old = menuService.getById(menu.getId());
                    BeanUtil.merge(old, menu);
                    menu.setUpdateTime(new Date());
                    menuService.update(old);
                } else {
                    Integer maxSort = 0; // 自动計算排序值
                    if (null != menu.getParent() && null != menu.getParent().getId()) {
                        Menu parent = menuService.getById(menu.getParent().getId());
                        menu.setParent(parent);
                        maxSort = menuService.getMaxSortByParent(menu.getParent().getId());
                        menu.setSort(maxSort + 1);
                        menu.setLevel(parent.getLevel() + 1);
                    } else {
                        // 一级菜单
                        menu.setParent(null);
                        menu.setLevel(1);
                        maxSort = menuService.getMaxSortByParent(null);
                        menu.setSort(maxSort + 1);
                        menu.setMenuUrl(AppConstants.DEFAULT_MENU_URL);
                    }
                    menu.setCreateTime(new Date());
                    menuService.save(menu);
                }
                respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.SAVE_SUCCESS), response);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.SAVE_ERROR), response);
                logger.error(AppConstants.configMap.get(AppConstants.SAVE_ERROR) + e);
            }
        }

    }

    /**
     * 刪除指定菜单
     * 
     * @param id 菜单ID
     * @author H2013788
     */
    @RequestMapping("/delete_menu")
    public void deleteMenu(Integer id, HttpServletResponse response) {
        try {
            if (null != id) {
                menuService.deleteById(id);
                respEasyuiSuccessResult(AppConstants.configMap.get(AppConstants.OPERATE_SUCCESS), response);
            } else {
                respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.REQUEST_PARAM_NULL), response);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            respEasyuiErrorResult(AppConstants.configMap.get(AppConstants.OPERATE_ERROR), response);
            logger.error(AppConstants.configMap.get(AppConstants.DELETE_ERROR) + e);
        }
    }

    /**
     * 查询菜单列表，输出樹形結構，用於添加菜单时选择父级菜单
     * 
     * @author H2013788
     * @date 2017/11/15下午4:52:52
     */
    @SuppressWarnings("unchecked")
    @RequestMapping("/treelist")
    public void treeList(HttpServletResponse response) {
        // 查询最大菜单级別数值，用於拼裝樹形数据
        int maxLevel = menuService.getMaxLevel();
        // 所有菜单列表
        PagerFilter pagerFilter = getPageableByNoPage();
        pagerFilter = menuService.listByPager(null, null, pagerFilter);
        List<Menu> menuList = pagerFilter.getObjs();
        List<RoleMenuVo> list = new ArrayList<RoleMenuVo>();
        list = Data2TreeVoUtils.buildMenuTreeVo(maxLevel, null, menuList);
        Gson gson = new Gson();
        writeResponse(new StringBuffer(gsonDateTime.toJson(list)), response);
    }

}
